<template>
  <div ref="root" :style="style"></div>
</template>
<script>
import { ref, watch, nextTick, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'

export default {
  props: ['option', 'style'],
  setup(props) {
    let charts
    const root = ref()

    nextTick(() => {
      charts = echarts.init(root.value, {
        color: [
          '#0082F2',
          '#21CB97',
          '#F2BE49',
          '#fe6868',
        ]
      })

      charts.setOption(props.option)
    })

    watch(() => props.option, () => charts.setOption(props.option))

    onMounted(() => {
      window.addEventListener('resize', () => charts.resize())
    })

    onUnmounted(() => {
      window.removeEventListener('resize', () => charts.resize())
    })

    const clear = () => charts.clear()

    return {
      clear,
      root
    }
  }
}
</script>